$(function () {
    $(`#link_reg`).on(`click`, function () {
        $(this).parents(`.login-box`).hide().siblings(`.reg-box`).show();
    })

    $(`#link_login`).on(`click`, function () {
        $(this).parents(`.reg-box`).hide().siblings(`.login-box`).show();
    })

    var form = layui.form;
    form.verify({
        // 自定义了一个叫做 pwd 校验规则
        pwd: [/^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'],
        sure: function (value) {
            var pwd = $(`.reg-box [name=password]`).val();
            if (pwd != value) {
                return `两次密码不一致`
            }
        }
    })

    var layer = layui.layer
    //注册
    $(`#form_reg`).on(`submit`, function (e) {
        e.preventDefault();
        var username = $(`.reg-box [name=username]`).val();
        var password = $(`.reg-box [name=password]`).val();
        $.ajax({
            type: `post`,
            url: `/api/reguser`,
            data: {
                username: username,
                password: password
            },
            success: function (res) {
                if (res.status != 0) {
                    return layer.msg(res.message)
                }
                layer.msg('注册成功，请登录！');
                $('#link_login').click();
            }
        })
    })

    //登录
    $(`#form_login`).on(`submit`, function (e) {
        e.preventDefault();
        var username = $(`.login-box [name=username]`).val();
        var password = $(`.login-box [name=password]`).val();
        $.ajax({
            type: `post`,
            url: `/api/login`,
            data: {
                username: username,
                password: password
            },
            success: function (res) {
                console.log(res);
                if (res.status != 0) {
                    return layer.msg(`登录失败`);
                }
                layer.msg('登录成功');
                //在本地存储请求成功的token
                localStorage.setItem(`token`, res.token);
                //页面跳转
                location.href = `/index.html`;
            }
        })
    })

})